package vno.fux.map
{
	import flash.display.Sprite;
	
	import vno.fux.res.pool.ResourcePool;
	import vno.fux.res.pool.MapResource;
	import vno.fux.res.pool.MapTile;
	import vno.fux.res.manager.ResourceManager;
	import flash.events.Event;

	public class MapTilesView extends BaseMapView
	{
		public static const NAME:String = "TilesView";
		private var _tilesContainer:Sprite;
		private var _mapView:Sprite;
		private var _midTile:MapTile;
		private var _tileWidth:uint;
		private var _tileHeight:uint;
		private var _tileNumX:uint;
		private var _tileNumY:uint;
		
		public function MapTilesView(model_:MapModel, controller_:MapController)
		{
			super(model_, controller_);
			_tilesContainer = new Sprite;
			_tileWidth = model_.tileWidth;
			_tileHeight = model_.tileHeight;
			_tileNumX = model_.tileNumX;
			_tileNumY = model_.tileNumY;
			
			//ResourceManager.getInstance().map.loadMapTiles(0,0);
			_midTile = (ResourcePool.getInstance().mapRes.getRes(_model.id) as MapResource).mapTile(0,0);
			_tilesContainer.addChild(_midTile);
			
			this.content = _tilesContainer;
		}
		
		override public function update(evt:Event):void
		{
			this.setRegPoint([_model.ox, _model.oy]);
			loadTiles();
		}
		
		public function loadTiles():void
		{
			_tilesContainer.removeChildren();
			var tiles:Function = (ResourcePool.getInstance().mapRes.getRes(_model.id) as MapResource).mapTile;
			var _midX:int = _model.ox/_tileWidth;
			var _midY:int = _model.oy/_tileHeight;
			_midTile = tiles(_midX, _midY);
			var rangeX:int = Math.ceil(stage.stageWidth/_tileWidth);
			var rangeY:int = Math.ceil(stage.stageHeight/_tileHeight);
			var startX:int = _midX - rangeX/2 +1;
			var startY:int = _midY - rangeY/2 +1;
			startX = startX>=1?startX-1:0;
			startY = startY>=1?startY-1:0;
			var endX:int = (startX+rangeX+1)<(_tileNumX)?startX+rangeX+2:_tileNumX;
			var endY:int = (startY+rangeY+1)<(_tileNumY)?startY+rangeY+2:_tileNumY;
			for(var i:int = startX; i<endX; i++)
			{
				for(var j:int = startY; j<endY; j++)
				{
					var mapTile:MapTile = tiles(i, j);
					mapTile.x = i*_tileWidth;
					mapTile.y = j*_tileHeight;
					_tilesContainer.addChild(mapTile);
				}
			}
		}
	}
}